package com.cloud.utils;//package com.hty.hbase;

import com.cloud.entity.CloudLogRecordReqQuery;
import com.cloud.config.HbaseConfig;
import com.cloud.entity.CloudLogRecord;
import com.cloud.entity.HbaseEntity;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.client.coprocessor.AggregationClient;
import org.apache.hadoop.hbase.client.coprocessor.LongColumnInterpreter;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//控制依赖顺序，保证springContextHolder类在之前已经加载
@DependsOn("springContextHolder")
@Component
@Slf4j
public class HBaseUtils {
    //手动获取hbaseConfig配置类对象
    private static HbaseConfig hbaseConfig = SpringContextHolder.getBean("hbaseConfig");
    private static Configuration conf = HBaseConfiguration.create();
    //设置hbase连接池
    private static ExecutorService pool = Executors.newFixedThreadPool(1);
    private static Connection connection = null;
    private volatile static String rowkey = null;
    private volatile static Long sum = 0L;
//    //key是类名 value是类下面对应的field集合
//    private volatile static Map<String, List<Field>> fieldsMap = new HashMap();

//    @Autowired
//    private ConsumerLogProperties consumerLogProperties;

    private HBaseUtils() {
        //初始化rowkey
        rowkey = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        //初始化连接池
        if (connection == null) {
            try {
                //将hbase配置类中定义的配置加载到连接池中每个连接里
                Map<String, String> confMap = hbaseConfig.getConfMaps();
                for (Map.Entry<String, String> confEntry : confMap.entrySet()) {
                    conf.set(confEntry.getKey(), confEntry.getValue());
                }
                connection = ConnectionFactory.createConnection(conf, pool);
            } catch (IOException e) {
                log.error("HbaseUtils实例初始化失败！错误信息为：" + e.getMessage(), e);
            }
        }
    }

    //关闭连接
    public void closeConnection() throws Exception {
        if (connection != null) {
            connection.close();
        }
    }

    /**
     * 获取rowkey
     * 生成策略：生成时间唯一随机数
     */
    public String getRowkey() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //多线程调用该方法只有一个能获取到值，其他进行阻塞
        synchronized (HBaseUtils.class) {
            Date date = new Date();
            String key = format.format(date);
            //为了做判断（跨年12月与1月），所以加上年月，实际rowkey从日开始就行，因为每个月都会生成一张新表
            if (Long.valueOf(key) > Long.valueOf(rowkey)) {
                rowkey = key;
                return rowkey;
            }
            //多个线程同一毫秒，将下一个加1，一般不会走到
            rowkey = String.valueOf(Long.parseLong(rowkey) + 1);
            return rowkey;
        }
    }

    /**
     * 创建表(不加协处理器)
     *
     * @param tableName
     * @param familyColumnName 列簇名
     */
    public Boolean createTable(String tableName, List<String> familyColumnName) throws Exception {
        Admin admin = connection.getAdmin();

        try {
            byte[][] splitKeys = new byte[][]{
                    Bytes.toBytes("1-"),
                    Bytes.toBytes("2-"),
                    Bytes.toBytes("3-"),
                    Bytes.toBytes("4-"),
                    Bytes.toBytes("5-"),
                    Bytes.toBytes("6-"),
                    Bytes.toBytes("7-"),
                    Bytes.toBytes("8-"),
                    Bytes.toBytes("9-")};

            //表存在，则不创建
            if (admin.tableExists(TableName.valueOf("cloud:" + tableName))) {
                admin.close();
                return false;
            }
            TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(TableName.valueOf("cloud:" + tableName));
            familyColumnName.forEach(columnFamily -> {
                ColumnFamilyDescriptorBuilder cfDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(columnFamily));
                cfDescriptorBuilder.setMaxVersions(1);
                ColumnFamilyDescriptor familyDescriptor = cfDescriptorBuilder.build();
                tableDescriptor.setColumnFamily(familyDescriptor);
            });
            admin.createTable(tableDescriptor.build(), splitKeys);
        } catch (Exception e) {
            log.error("创建表失败异常：" + e);
        } finally {
            admin.close();
        }
        return true;
    }

    /**
     * 创建表+协处理器
     *
     * @param tableName
     * @param familyColumnName 列簇名
     */
    public Boolean createTableAndCoprocessor(String tableName, List<String> familyColumnName) throws Exception {
        Admin admin = connection.getAdmin();
        try {
            byte[][] splitKeys = new byte[][]{
                    Bytes.toBytes("1-"),
                    Bytes.toBytes("2-"),
                    Bytes.toBytes("3-"),
                    Bytes.toBytes("4-"),
                    Bytes.toBytes("5-"),
                    Bytes.toBytes("6-"),
                    Bytes.toBytes("7-"),
                    Bytes.toBytes("8-"),
                    Bytes.toBytes("9-")};

            //表存在，则不创建
            if (admin.tableExists(TableName.valueOf("cloud:" + tableName))) {
                admin.close();
                return false;
            }
            TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(TableName.valueOf("cloud:" + tableName));
            //协处理器
            String coprocessorClass = "org.apache.hadoop.hbase.coprocessor.AggregateImplementation";
            tableDescriptor.addCoprocessor(coprocessorClass);

            familyColumnName.forEach(columnFamily -> {
                ColumnFamilyDescriptorBuilder cfDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(columnFamily));
                cfDescriptorBuilder.setMaxVersions(1);
                ColumnFamilyDescriptor familyDescriptor = cfDescriptorBuilder.build();
                tableDescriptor.setColumnFamily(familyDescriptor);
            });
            admin.createTable(tableDescriptor.build(), splitKeys);
        } catch (Exception e) {
            log.error("创建表失败异常：" + e);
        } finally {
            admin.close();
        }
        return true;
    }

    /**
     * 删除 hBase 表
     *
     * @param tableName 表名
     */
    public boolean deleteTable(String tableName) throws Exception {
        HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
        try {
            // 删除表前需要先禁用表
            admin.disableTable(TableName.valueOf("cloud:" + tableName));
            admin.deleteTable(TableName.valueOf("cloud:" + tableName));
        } catch (Exception e) {
            log.error("删除表失败：" + e);
        } finally {
            admin.close();
        }
        return true;
    }

    /**
     * 拉取数据-通过rowkey
     *
     * @param tableName 表名
     * @param rowKey
     */
    public List<Map> getRow(String tableName, String rowKey) {
        try {
            Table table = connection.getTable(TableName.valueOf("cloud:" + tableName));
            Get get = new Get(Bytes.toBytes(rowKey));
            Result result = table.get(get);
            if (result != null) {

                List results = new ArrayList();
                List<Cell> cells = result.listCells();
                for (Cell cell : cells) {
                    //获取列的名称
                    String columnName = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
                    String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
                    Map map = new HashMap();
                    map.put(columnName, value);
                    results.add(map);
                }
                return results;
            }
        } catch (IOException e) {
            log.error("查询hbase失败：" + e);
        }
        return null;
    }

    /**
     * 拉取数据-通过条件
     */
    public List<Map> selectByFilter(CloudLogRecordReqQuery cloudLogRecordReqQuery) throws IOException {
        if (cloudLogRecordReqQuery == null || StringUtils.isBlank(cloudLogRecordReqQuery.getTableName())) {
            log.info("查询条件错误（表名必传），参数是：" + cloudLogRecordReqQuery);
            return null;
        }

        Table table = connection.getTable(TableName.valueOf("cloud:" + cloudLogRecordReqQuery.getTableName()));
        List<Filter> filters = new ArrayList<Filter>();

        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getSourceApplicationName())) {
            Filter filterSource = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("source"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getSourceApplicationName()));
            filters.add(filterSource);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getTargetApplicationName())) {
            Filter filterTarget = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("target"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getTargetApplicationName()));
            filters.add(filterTarget);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getSkyTraceId())) {
            Filter filterSkId = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("skId"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getSkyTraceId()));
            filters.add(filterSkId);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getReqAddr())) {
            Filter filterAddr = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("addr"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getReqAddr()));
            filters.add(filterAddr);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getTraceId())) {
            Filter filterTId = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("tId"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getTraceId()));
            filters.add(filterTId);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getReqStartTime()) && StringUtils.isNotBlank(cloudLogRecordReqQuery.getReqEndTime())) {
            Filter filterReqTimeLess = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("reqTime"), CompareFilter.CompareOp.LESS_OR_EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getReqEndTime()));
            filters.add(filterReqTimeLess);
            Filter filterReqTimeGreater = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("reqTime"), CompareFilter.CompareOp.GREATER_OR_EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getReqStartTime()));
            filters.add(filterReqTimeGreater);
        }
        FilterList filterList = new FilterList(filters);
        Scan scan = new Scan();
        scan.setFilter(filterList);
        ResultScanner rs = table.getScanner(scan);
        List results = new ArrayList();

        if (rs != null) {
            for (Result r : rs) {
                List res = new ArrayList();
                if (!CollectionUtils.isEmpty(r.listCells())) {
                    for (Cell cell : r.listCells()) {
                        //获取列的名称
                        String columnName = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
                        String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
                        Map map = new HashMap();
                        map.put(columnName, value);
                        res.add(map);
                    }
                }
                results.add(res);
            }
        }
        return results;
    }

    /**
     * 查询数据数量-通过rowkey查询（直接加时间）
     *
     * @param tableName   表名
     * @param startRowkey 开始Rowkey
     * @param stopRowkey  结束Rowkey
     */
    @SneakyThrows
    public Long getCount(String tableName, String startRowkey, String stopRowkey) {
        try {
            TableName name = TableName.valueOf("cloud:" + tableName);
            Scan scan = new Scan();
            if (StringUtils.isNotBlank(startRowkey) && StringUtils.isNotBlank(stopRowkey)) {
                scan.setStartRow(startRowkey.getBytes());
                scan.setStopRow(stopRowkey.getBytes());
            }
            AggregationClient aggregationClient = new AggregationClient(conf);
            Long count = aggregationClient.rowCount(name, new LongColumnInterpreter(), scan);
            log.info("RowCount: " + count);
            return count;
        } catch (IOException e) {
            log.error("查询hbase失败：" + e);
        }
        return null;
    }

    /**
     * 查询数据数量-通过rowkey查询（直接加时间）
     *
     * @param tableName   表名
     * @param startRowkey
     * @param stopRowkey
     */
    @SneakyThrows
    public Long getAllCount(String tableName, String startRowkey, String stopRowkey) {
        TableName name = TableName.valueOf("cloud:" + tableName);
        AggregationClient aggregationClient = new AggregationClient(conf);
        Scan scan = new Scan();
        Long sum = 0L;
        if (StringUtils.isNotBlank(startRowkey) && StringUtils.isNotBlank(stopRowkey)) {
            for (int i = 0; i < 10; i++) {
                String start = i + "-" + startRowkey;
                String end = i + "-" + stopRowkey;
                scan.setStartRow(start.getBytes());
                scan.setStopRow(end.getBytes());
                sum = sum + aggregationClient.rowCount(name, new LongColumnInterpreter(), scan);
            }
        } else {
            sum = aggregationClient.rowCount(name, new LongColumnInterpreter(), scan);
        }
        log.info("RowCount: " + sum);
        return sum;
    }

    /**
     * 查询数据数量-通过条件查询
     */
    @SneakyThrows
    public Long getAllCountByFilter(CloudLogRecordReqQuery cloudLogRecordReqQuery) {

        if (cloudLogRecordReqQuery == null || StringUtils.isBlank(cloudLogRecordReqQuery.getTableName())) {
            log.info("查询条件错误（表名必传）：" + cloudLogRecordReqQuery);
            return null;
        }
        TableName name = TableName.valueOf("cloud:" + cloudLogRecordReqQuery.getTableName());
        AggregationClient aggregationClient = new AggregationClient(conf);

        Table table = connection.getTable(name);
        List<Filter> filters = new ArrayList<Filter>();

        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getSourceApplicationName())) {
            Filter filterSource = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("source"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getSourceApplicationName()));
            filters.add(filterSource);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getTargetApplicationName())) {
            Filter filterTarget = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("target"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getTargetApplicationName()));
            filters.add(filterTarget);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getSkyTraceId())) {
            Filter filterSkId = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("skId"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getSkyTraceId()));
            filters.add(filterSkId);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getReqAddr())) {
            Filter filterAddr = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("addr"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getReqAddr()));
            filters.add(filterAddr);
        }
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getTraceId())) {
            Filter filterTId = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("tId"), CompareFilter.CompareOp.EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getTraceId()));
            filters.add(filterTId);
        }

        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getReqStartTime()) && StringUtils.isNotBlank(cloudLogRecordReqQuery.getReqEndTime())) {
            Filter filterReqTimeLess = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("reqTime"), CompareFilter.CompareOp.LESS_OR_EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getReqEndTime()));
            filters.add(filterReqTimeLess);
            Filter filterReqTimeGreater = new SingleColumnValueFilter(
                    Bytes.toBytes("logs"), Bytes.toBytes("reqTime"), CompareFilter.CompareOp.GREATER_OR_EQUAL, Bytes.toBytes(cloudLogRecordReqQuery.getReqStartTime()));
            filters.add(filterReqTimeGreater);
        }
        FilterList filterList = new FilterList(filters);
        Scan scan = new Scan();
        scan.setFilter(filterList);

        Long sum = 0L;
        if (StringUtils.isNotBlank(cloudLogRecordReqQuery.getStartRowKey()) && StringUtils.isNotBlank(cloudLogRecordReqQuery.getEndRowKey())) {
            for (int i = 0; i < 10; i++) {
                String start = i + "-" + cloudLogRecordReqQuery.getStartRowKey();
                String end = i + "-" + cloudLogRecordReqQuery.getEndRowKey();
                scan.setStartRow(start.getBytes());
                scan.setStopRow(end.getBytes());
                sum = sum + aggregationClient.rowCount(name, new LongColumnInterpreter(), scan);
            }
        } else {
            sum = aggregationClient.rowCount(name, new LongColumnInterpreter(), scan);
        }
        log.info("RowCount: " + sum);
        return sum;
    }

    /**
     * 单条插入
     *
     * @param tableName        表名
     * @param columnFamilyName 列簇
     * @param pairList         传递的值
     */
    public boolean putRow(String tableName,
                          String columnFamilyName,
                          List<Pair<String, String>> pairList) throws Exception {
        Table table = connection.getTable(TableName.valueOf("cloud:" + tableName));
        try {
            String rowkey = this.getRowkey();
            Put put = new Put(Bytes.toBytes(rowkey));
            pairList.forEach(pair -> put.addColumn(
                    Bytes.toBytes(columnFamilyName),
                    Bytes.toBytes(pair.getFirst()),
                    Bytes.toBytes(pair.getSecond()))
            );
            table.put(put);
        } catch (Exception e) {
            log.error("插入hbase失败：" + e);
        }
        table.close();
        return true;
    }

    /**
     * 批量添加数据
     * rowKey生成策略：9-10141252315058499
     * 9：批量插入的条数对10取余，如批量条数是500，则末尾499对10取模9
     * 10141252315 ：是上面getRowKey的唯一时间戳去除年月
     * 058：是三位随机数，保证多节点rowkey的唯一
     * 499是批量插入500条每一条的循环序列号，如001，002，499
     *
     * @param tableName        表名
     * @param columnFamilyName 列明
     * @param objects          传递的list对象
     */
    public boolean insertDataList(String tableName,
                                  String columnFamilyName, List<HbaseEntity> objects) throws Exception {
        Table table = connection.getTable(TableName.valueOf("cloud:" + tableName));
        try {
            if (CollectionUtils.isEmpty(objects)) {
                return false;
            }
            //获取随机数
            String rowkey = this.getRowkey();
            //批量插入的数量
            Integer batchSize = 1;
            int batchSizeLeng = batchSize.toString().length();

            List<Put> list = new ArrayList<Put>();
            for (int i = 0; i < objects.size(); i++) {
                List<Pair<String, String>> pairList = converPair(objects.get(i));
                String end = String.format("%0" + batchSizeLeng + "d", i);
                //随机数，防止多pod导致key重复，后期可以分布式锁
                String random = String.format("%03d", (int) (Math.random() * 1000));
                int start = Integer.parseInt(end) % 10;
                String newRowkeys = start + "-" + rowkey.substring(6) + random + end;
                if (i == 0) {
                    log.info("start插入的rowkey是：：：" + newRowkeys);
                }
                if (i == objects.size() - 1) {
                    log.info("end插入的rowkey是：：：" + newRowkeys);
                }
                Put put = new Put(Bytes.toBytes(newRowkeys));
                pairList.forEach(pair -> put.addColumn(
                        Bytes.toBytes(columnFamilyName),
                        Bytes.toBytes(pair.getFirst()),
                        Bytes.toBytes(pair.getSecond())));
                list.add(put);
            }
            table.put(list);

        } catch (Exception e) {
            log.error("插入hbase失败：" + e);
        }
        table.close();
        return true;
    }

    /**
     * 批量添加数据
     *
     * @param tableName        表名
     * @param columnFamilyName 列明
     * @param objects          传递的list对象
     */
    public boolean insertDataListSync(String tableName,
                                      String columnFamilyName, List<HbaseEntity> objects) throws Exception {
        Table table = connection.getTable(TableName.valueOf("cloud:" + tableName));

        try {
            if (CollectionUtils.isEmpty(objects)) {
                return false;
            }

            String rowkey = this.getRowkey();

            List<Put> list = new ArrayList<Put>();
            for (int i = 0; i < objects.size(); i++) {
                List<Pair<String, String>> pairList = converPair(objects.get(i));
                String end = String.format("%06d", i);
                int start = Integer.parseInt(end) % 10;
                String newRowkeys = start + "-" + rowkey.substring(6) + end;
                if (i == 0) {
                    pairList.forEach(pair -> {
                        if (pair.getFirst().equals("id")) {
                            log.info("insert线程==" + Thread.currentThread().getName() + ",批量insert插入第一个id==" + pair.getSecond());
                        }
                    });
                    log.info("start插入的rowkey是：：：" + newRowkeys);
                }
                if (i == objects.size() - 1) {
                    pairList.forEach(pair -> {
                        if (pair.getFirst().equals("id")) {
                            log.info("insert线程==" + Thread.currentThread().getName() + ",批量insert插入最后一个id==" + pair.getSecond());
                        }
                    });
                    log.info("end插入的rowkey是：：：" + newRowkeys);
                }
                Put put = new Put(Bytes.toBytes(newRowkeys));
                pairList.forEach(pair -> put.addColumn(
                        Bytes.toBytes(columnFamilyName),
                        Bytes.toBytes(pair.getFirst()),
                        Bytes.toBytes(pair.getSecond())));
                list.add(put);
            }
            table.put(list);
            synchronized (CloudLogRecord.class) {
                sum = sum + 1;
                log.info("sum===" + sum);
            }
        } catch (Exception e) {
            log.error("插入hbase失败：" + e);
        }
        table.close();
        return true;
    }

    /**
     * 删除指定行记录
     *
     * @param tableName 表名
     * @param rowKey    唯一标识
     */
    public static boolean deleteRow(String tableName, String rowKey) {
        try {
            Table table = connection.getTable(TableName.valueOf("cloud:" + tableName));
            Delete delete = new Delete(Bytes.toBytes(rowKey));
            table.delete(delete);
        } catch (Exception e) {
            log.error("删除hbase失败：" + e);
        }
        return true;
    }

    public List<Pair<String, String>> converPair(HbaseEntity entitie) {
        if (entitie == null) {
            return null;
        }
        List<Pair<String, String>> pairList = new ArrayList();
        if (StringUtils.isNotBlank(entitie.getId())) {
            Pair<String, String> objectPair = new Pair<>("id", entitie.getId());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getReqUser())) {
            Pair<String, String> objectPair = new Pair<>("reqUser", entitie.getReqUser());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getAcctType())) {
            Pair<String, String> objectPair = new Pair<>("acctType", entitie.getAcctType());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getSource())) {
            Pair<String, String> objectPair = new Pair<>("source", entitie.getSource());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getTarget())) {
            Pair<String, String> objectPair = new Pair<>("target", entitie.getTarget());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getReqTime())) {
            Pair<String, String> objectPair = new Pair<>("reqTime", entitie.getReqTime());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getType())) {
            Pair<String, String> objectPair = new Pair<>("type", entitie.getType());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getAddr())) {
            Pair<String, String> objectPair = new Pair<>("addr", entitie.getAddr());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getSkId())) {
            Pair<String, String> objectPair = new Pair<>("skId", entitie.getSkId());
            pairList.add(objectPair);
        }
        if (StringUtils.isNotBlank(entitie.getTId())) {
            Pair<String, String> objectPair = new Pair<>("tId", entitie.getTId());
            pairList.add(objectPair);
        }
        return pairList;
    }

//    public <T> List<Pair<String, String>> getParentField(T obj) throws Exception {
//        List<Pair<String, String>> pairList = new ArrayList();
//        Class<?> aClass = obj.getClass();
//        //查询cloudLogRecordFields是否存在，不存在的话初始化之后放到全局变量
//        if (CollectionUtils.isEmpty(fieldsMap.get(aClass.getSimpleName()))) {
//
//            List<Field> allFields = new ArrayList<>(100);
//            // 获取当前对象的所有属性字段
//            // clazz.getFields()：获取public修饰的字段
//            // clazz.getDeclaredFields()： 获取所有的字段包括private修饰的字段
//            allFields.addAll(Arrays.asList(aClass.getDeclaredFields()));
//
//            // 获取所有父类的字段， 父类中的字段需要逐级获取
//            Class clazzSuper = aClass.getSuperclass();
//
//            // 如果父类不是object，表明其继承的有其他类。 逐级获取所有父类的字段
//            while (clazzSuper != Object.class) {
//                allFields.addAll(Arrays.asList(clazzSuper.getDeclaredFields()));
//                clazzSuper = clazzSuper.getSuperclass();
//            }
//
//            fieldsMap.put(aClass.getSimpleName(), allFields);
//
//        }
//        fieldsMap.get(aClass.getSimpleName()).stream().forEach(field -> {
//            // 设置字段可访问， 否则无法访问private修饰的变量值
//            field.setAccessible(true);
//            try {
//                // 获取字段名称
//                String fieldName = field.getName();
//                // 获取指定对象的当前字段的值
//                Object fieldVal = null;
//                if ("java.util.Date".equals(field.getType().getName()) && field.get(obj) != null) {
//
//                    fieldVal = sdf.format((Date) field.get(obj));
//                } else {
//                    fieldVal = field.get(obj);
//                }
//
//                if (fieldVal != null) {
//                    Pair<String, String> objectPair = new Pair<>(fieldName, String.valueOf(fieldVal));
//                    pairList.add(objectPair);
//                }
//            } catch (Exception e) {
//                log.error("反射获取值错误：" + e);
//            }
//        });
//        return pairList;
//    }
}
